<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <vxe-grid ref='storeMaterialGrid' v-bind="gridOptions" class="my-grid66" :cell-style="rowStyle">
        <!--搜索表单 -->
        <template #form>
          <a-form
            :model="where"
            :label-col="{md: {span: 7}, sm: {span: 24}}"
            :wrapper-col="{md: {span: 17}, sm: {span: 24}}">
            <a-row>
              <a-col :lg="5" :md="12" :sm="24"
                     :xs="24">
                <a-form-item label="材料名称:" name="name">
                  <a-input
                    v-model:value="where.name"
                    placeholder="通过材料名称查询"
                    :min="0"
                    class="ele-fluid">
                  </a-input>
                </a-form-item>
              </a-col>

              <a-col :lg="19" :md="12" :sm="24" :xs="24">
                <a-form-item class="ele-text-right" :wrapper-col="{span: 24}">
                  <a-space>
                    <a-button type="primary" @click="reload">查询</a-button>
                    <a-button @click="reset">重置</a-button>
                  </a-space>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </template>
        <!--自定义按钮-->
        <!--        <template #bottom>-->
        <!--          <div>-->
        <!--            <br/>-->
        <!--            <a-alert message="Informational Notes" type="info"-->
        <!--                     description="Detailed description and advices about successful copywriting."-->
        <!--                     show-icon/>-->
        <!--            <br/>-->
        <!--          </div>-->

        <!--        </template>-->

        <template #operate="{ row }">
          <a-space>
<!--            <a class="ele-text-warning" @click="viewEvent(row)">查看</a>-->
<!--            <a-divider type="vertical"/>-->
            <a class="ele-text-success" @click="outgoing(row,2)">领用</a>
            <a-divider type="vertical"/>
            <a class="ele-text-warning" @click="outgoing(row,3)">损耗</a>
            <a-divider type="vertical"/>
            <a class="ele-text-danger" @click="outgoing(row,0)">退库</a>

          </a-space>
        </template>


        <!--TODO:自定义列模板-->
        <template #dddd="{  }">
          <a href="http://showdoc.cqcflq.com/">文档地址</a>
        </template>

        <template #ycs>
          <a-space>
            <a-button type="primary" @click="addEvent(1)">
              <template #icon>
                <plus-outlined/>
              </template>
              <span>材料入库</span>
            </a-button>
            <a-button type="primary" @click="inputFromOrder()">
              <template #icon>
                <plus-outlined/>
              </template>
              <span>通过订单导入</span>
            </a-button>
<!--            <a-button type="danger" @click="addEvent(0)">-->
<!--              <template #icon>-->
<!--                <delete-outlined/>-->
<!--              </template>-->
<!--              <span>退库</span>-->
<!--            </a-button>-->

            <a-button @click="gridOptions.sortConfig.multiple=!gridOptions.sortConfig.multiple">
              <template #icon>
                <upload-outlined/>
              </template>
              <span>{{ gridOptions.sortConfig.multiple === false ? '单' : '多' }}字段排序</span>
            </a-button>
          </a-space>
        </template>
      </vxe-grid>

      <!--编辑弹窗-->
      <vxe-modal v-model="storeMaterialListApp.editModalShowing" ref="storeMaterialEditModal"
                 :title="gridOptions.showEditTitle"
                 id="storeMaterialEditModal"
                 width="800" height="400" min-width="460" min-height="320" :lock-view="false" :mask="false"
                 show-footer show-zoom resize remember storage transfer dblclickZoom
                 :destroy-on-close="true"
      >
        <template #default>
          <div id="storeMaterialEditModalContent">
          </div>
        </template>
        <template #footer>
          <div id="storeMaterialEditModalFooter">
          </div>
          <teleport to="#storeMaterialEditModalContent">
            <storeMaterial-edit ref="storeMaterial-edit" @editClose="getEditClose"/>
          </teleport>
        </template>
      </vxe-modal>

      <!--查看弹窗-->
      <vxe-modal v-model="storeMaterialListApp.viewModalShowing" :title="gridOptions.showDetailsTitle"
                 id="storeMaterialViewModal"
                 width="600"
                 min-width="460"
                 min-height="320"
                 :destroy-on-close="true"
                 :lock-view="false" :mask="false"
                 footer
                 show-footer show-zoom resize remember storage transfer dblclickZoom>
        <template #default>
          <storeMaterial-detail ref="storeMaterial-detail"/>
        </template>
      </vxe-modal>

      <!-- 通过订单导入弹窗-->
      <vxe-modal v-model="storeMaterialListApp.orderInputShowing" id="storeMaterialOrderInputViewModal"
                 title="通过订单导入" width="800" height="400" min-width="460" min-height="320" :lock-view="false"
                 :mask="false"
                 show-footer show-zoom resize remember storage transfer dblclickZoom
                 :destroy-on-close="true">
        <template #default>
          <div id="storeMaterialOrderInputModalContent">
          </div>
        </template>
        <template #footer>
          <div id="storeMaterialOrderInputModalFooter">
          </div>
          <teleport to="#storeMaterialOrderInputModalContent">
            <storeMaterial-orderInput ref="storeMaterial-orderInput" @editClose="getEditClose"/>
          </teleport>
        </template>
      </vxe-modal>
      <!--退库领用弹窗-->
      <vxe-modal v-model="storeMaterialListApp.outgoingShowing" id="storeMaterialOutgoingViewModal"
                 :title="storeMaterialListApp.outgoingTittle" :lock-view="false" :mask="false" width="600"
                 min-width="460"
                 min-height="320" :destroy-on-close="true" footer
                 show-footer show-zoom resize remember storage transfer dblclickZoom>
        <template #default>
          <div id="storeMaterialOutgoingModalContent">
          </div>
        </template>
        <template #footer>
          <div id="storeMaterialOutgoingModalFooter">
          </div>
          <teleport to="#storeMaterialOutgoingModalContent">
            <StoreMaterialOrderOutgoing ref="storeMaterial-outgoing" @editClose="getEditClose"
                                        :defaultOperation="storeMaterialListApp.outgoingOperation"/>
          </teleport>
        </template>
      </vxe-modal>
    </a-card>
  </div>
</template>

<script>
import {defineComponent, reactive, ref, toRefs, provide} from 'vue'//, Ref
import {VXETable} from 'vxe-table'//, VxeGridInstance, VxeGridProps
import {StoreMaterialService} from "@/views/restaurant/material/storeMaterial/storeMaterialService";
import StoreMaterialEdit
  from "@/views/restaurant/material/storeMaterial/storeMaterial-edit";
import StoreMaterialDetail
  from "@/views/restaurant/material/storeMaterial/storeMaterial-detail";
import StoreMaterialOrderInput
  from "@/views/restaurant/material/storeMaterial/storeMaterial-orderInput";
import StoreMaterialOrderOutgoing
  from "@/views/restaurant/material/storeMaterial/storeMaterial-outgoing";
import {
  PlusOutlined,
  // DeleteOutlined,
} from '@ant-design/icons-vue';


export default defineComponent({
  components: {
    StoreMaterialEdit,
    StoreMaterialDetail,
    StoreMaterialOrderOutgoing,
    StoreMaterialOrderInput,
    // DeleteOutlined,
    PlusOutlined,
  },
  setup() {
    const storeMaterialGrid = ref({})// as VxeGridInstance
    // 搜索表单是否展开
    let searchExpand = ref(false)
    let proxyInfo = reactive({})
    const where = ref({})
    const eid = ref({})
    const startIndex = ref({})
    const storeMaterialListApp = reactive({
      editModalShowing: false,
      viewModalShowing: false,
      orderInputShowing: false,
      outgoingShowing: false,
      outgoingTittle: '',
      outgoingOperation: null,
      editModalForEdit: false,
      addModalForEdit: false,
      orderInputForEdit: false
    })
    const rowStyle = ({ row }) => {
        if (row.quantity === 0) {
          return {
            backgroundColor: '#FFF1EE'
          }
        }
    }
    const gridOptions = reactive({
      border: true,
      resizable: true,
      showHeaderOverflow: true,
      showOverflow: true,
      highlightHoverRow: true,
      keepSource: true,
      id: 'storeMaterialsGrid',
      // maxHeight: "100%",//表格高度
      height: 800,
      rowId: 'eid',
      selectRow: null,
      showEdit: false,
      showDetails: false,
      showEditTitle: '新建',
      showDetailsTitle: '查看',
      formData: {},//自定义的
      detailData: [],
      startIndex: startIndex,
      printConfig: {
        columns: [
          {field: 'name'},
          {field: 'email'},
          {field: 'nickname'},
          {field: 'age'},
          {field: 'amount'}
        ]
      },
      /*TODO:排序配置 */
      sortConfig: {
        trigger: 'cell',
        remote: true,
        multiple: true,//多字段排序，默认单排序
        showIcon: true,
        // iconAsc: "fa fa-arrow-up fa-1x",
        // iconDesc: "fa fa-arrow-down fa-1x",
      },
      customConfig: {
        storage: true
      },
      /*TODO:过滤器配置*/
      filterConfig: {
        remote: true
      },
      /*TODO:分页配置*/
      pagerConfig: {
        pageSize: 10,
        pageSizes: [5, 10, 15, 20, 50]
      },
      /*TODO:工具栏配置*/
      toolbarConfig: {
        slots: {buttons: 'ycs'},
        refresh: true,
        import: false,
        export: false,
        print: false,
        zoom: true,
        custom: true
      },
      /*TODO:请求代理配置*/
      proxyConfig: {
        seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
        sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
        filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
        form: false, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
        // 对应响应结果 { result: [], page: { total: 100 } }
        props: {
          result: 'data.datas', // 配置响应结果列表字段
          total: 'data.totalCount', // 配置响应结果总页数字段
          message: 'data.msg'
        },
        /*TODO:请求*/
        ajax: {
          /*TODO:分页条件查询*/
          query: ({page, sorts, filters}) => {  // 接收 Promise

            const conditions = {...where.value}

            // 处理筛选条件
            filters.forEach(({property, values}) => {
              conditions[property] = values.join('$|$')
            })
            const queryParams = {}
            queryParams.currentPage = page.currentPage
            queryParams.pageSize = page.pageSize
            startIndex.value = (queryParams.currentPage - 1) * queryParams.pageSize + 1
            // // 处理筛选条件
            queryParams.filters = conditions;
            // // 处理排序条件
            queryParams.orderBys = sorts;
            //
            const $grid = storeMaterialGrid.value
            $grid.queryParams = queryParams
            return StoreMaterialService.findStoreMaterials(queryParams).catch(error => {
              VXETable.modal.message({content: `加载数据出错，原因是：${error.message}`, status: 'error'});

            })
          },
        }
      },

      /*TODO:数据表列*/
      columns: [
        /*多选checkbox 单选seq*/
        {type: 'seq', title: '#', width: 40},
        {type: 'checkbox', field: 'eid', title: 'ID', width: 100, sortable: true},
        {
          field: 'name',
          title: '材料名称',
          sortable: true
        },
        {
          field: 'quantity',
          title: '数量(kg)',
          sortable: true,
          formatter({cellValue}){
            if(cellValue!=null){
              return cellValue.toFixed(2)
            }
          }
        },
        {
          field: 'price',
          title: '最高价格(元/kg)',
          sortable: true,
          formatter({cellValue}){
            if(cellValue){
              return cellValue.toFixed(2)
            }
          }
        },
        {title: '操作', width: 250, slots: {default: 'operate'}}
      ],

      /*TODO:复选框配置*/
      checkboxConfig: {
        labelField: 'eid',
        reserve: false,
        highlight: false,
        range: true
      },
      /*TODO:编辑验证*/
      editRules: {
        name: [
          {required: true, message: 'app.body.valid.rName'},
          {min: 3, max: 50, message: '名称长度在 3 到 50 个字符'}
        ],
        email: [
          {required: true, message: '邮件必须填写'}
        ],
        role: [
          {required: true, message: '角色必须填写'}
        ]
      },
      editConfig: {
        trigger: 'click',
        mode: 'row',
        showStatus: true
      }
    })//as VxeGridProps
    provide('storeMaterialListApp', storeMaterialListApp)
    provide('gridOptions', gridOptions)

    /*TODO:新建事件*/
    const addEvent = (operation) => {
      storeMaterialListApp.operation = operation;
      storeMaterialListApp.editModalShowing = true
      storeMaterialListApp.currentId = null;
      storeMaterialListApp.addModalForEdit = true;
      gridOptions.showEditTitle = "新建";
    }

    /*TODO:编辑事件*/
    const editEvent = (row) => {
      storeMaterialListApp.editModalShowing = true
      storeMaterialListApp.currentId = row.eid;
      storeMaterialListApp.editModalForEdit = true;
      gridOptions.showEditTitle = "编辑";
    }
    const getEditClose = () =>{
      // debugger
      console.log("触发emit")
      reload()
      // console.log(editClose)
    }

    /*TODO:编辑关闭事件*/
    const editEventClose = () => {
      console.log(gridOptions.formData);
      VXETable.modal.message({content: '提交成功', status: 'success'})
    }

    /*TODO:查看事件*/
    const viewEvent = (row) => {
      storeMaterialListApp.currentId = row.eid;
      storeMaterialListApp.viewModalShowing = true
      gridOptions.showDetailsTitle = '查看';
    }

    // /*TODO:退库*/
    const outgoing = (row, operation) => {
      //修改
      storeMaterialListApp.currentId = row.eid;
      storeMaterialListApp.outgoingOperation = operation
      storeMaterialListApp.outgoingShowing = true;
      if (operation == 0) {
        storeMaterialListApp.outgoingTittle = '退库'
      } else if (operation == 2) {
        storeMaterialListApp.outgoingTittle = '领用'
      }else if (operation == 3){
        storeMaterialListApp.outgoingTittle = '损耗'
      }
      storeMaterialListApp.outgoingShowing = true
    }
    const onChange = (date, dateString) => {
      console.log(date)
      if (date.length !== 0) {
        console.log("添加")
        where.value.startDate = dateString[0]
        where.value.endDate = dateString[1]
      } else {
        console.log("清除")
        delete where.value.startDate
        delete where.value.endDate
        delete where.value.settleDate
      }
      console.log(where)

    }
    /*TODO:删除事件*/
    const deleteEvent = (row) => {
      StoreMaterialService.deleteStoreMaterial(row.eid).then(() => {
        VXETable.modal.message({content: '操作成功', status: 'success'})
      }).catch(error => {
        VXETable.modal.message({content: `系统错误，原因是：${error.message}`, status: 'error'});
      })
    }

    /*TODO:条件查询提交*/
    const reload = () => {
      const $grid = storeMaterialGrid.value
      $grid.commitProxy('query')//TODO:执行代理方法
    }
    /*TODO:重置搜索*/
    const reset = () => {
      where.value = {}
      const $grid = storeMaterialGrid.value
      $grid.commitProxy('query')//TODO:执行代理方法
    }
    /*TODO:通过订单导入*/
    const inputFromOrder = () => {
      storeMaterialListApp.orderInputShowing = true
      storeMaterialListApp.currentId = null;
      storeMaterialListApp.orderInputForEdit = true;
      gridOptions.showEditTitle = "通过订单导入";
    }

    //TODO:这里需要返回才能调用
    return {
      eid,
      storeMaterialGrid,
      gridOptions,
      searchExpand,
      getEditClose,
      onChange,
      inputFromOrder,
      rowStyle,
      outgoing,
      addEvent,
      editEvent,
      viewEvent,
      editEventClose,
      deleteEvent,
      where,
      reload,
      reset,
      storeMaterialListApp,
      ...toRefs(proxyInfo)
    }
  }
})
</script>

<style scoped>
.my-grid66 .alert-message {
  height: 40px;
  display: flex;
  align-items: center;
  margin: 10px 0;
  border-radius: 4px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.my-grid66 .alert-message-icon {
  width: 30px;
  text-align: center;
  color: #409eff;
  margin-right: 8px;
}

.my-grid66 .alert-message-content {
  flex-grow: 1;
  padding-right: 20px;
}

.my-grid66 .page-left {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
}

.my-grid66 .select-count {
  display: inline-block;
  vertical-align: middle;
}

.my-grid66 .my-input {
  width: 100%;
}

.my-grid66 .first-col {
  position: relative;
  height: 20px;
}

.my-grid66 .first-col:before {
  content: "";
  position: absolute;
  left: -15px;
  top: 10px;
  width: 110px;
  height: 1px;
  transform: rotate(28deg);
  background-color: #e8eaec;
}

.my-grid66 .first-col .first-col-top {
  position: absolute;
  right: 4px;
  top: -10px;
}

.my-grid66 .first-col .first-col-bottom {
  position: absolute;
  left: 4px;
  bottom: -10px;
}
</style>
